#! /bin/bash
#set -x
set -e

TempDir=/tmp/$(basename $0)_$(date +"%Y_%m_%d_%H_%M_%S")
VRuleListFile=$TempDir/.RuleList
BuildDir=$(dirname $(readlink $0))
TopMake=${BuildDir}/Makefile
GListBin=""

CFlags="-Wall -Os"

fatal()
{
  echo -e "$@" && echo "Exit .." && exit 1
}
WriteMake()
{
  echo -e "$@" >> ${TopMake}
}

[[ -L $0 ]] || fatal "Exec in the top of repo!"
[[ -e $VRuleListFile ]] && fatal "File ($VRuleListFile) exists!"
[[ -e ${TopMake} ]] && fatal "Makefile (${TopMake}) exists!"
mkdir -p $TempDir

# Generate Make Rules
WriteMake "default:"
if [ $# -eq 0 ] ; then
  find $(realpath ${BuildDir}) -name "makefile" > $VRuleListFile
else
  echo $(realpath $1/makefile.fake) > $VRuleListFile
fi
while read i
do
  LDirMake=$(dirname $i)
  LBinName=$(basename $LDirMake)
# WriteMake "\tmake -C ${LDirMake} download"
  WriteMake "\tmake -C ${LDirMake} checkout MAKE_PATH=${LDirMake}"
  WriteMake "\tmake -C ${LDirMake} build BIN_PATH=$LBinName"
  GListBin="${GListBin[@]} $LBinName"
done < $VRuleListFile

# Build
make -f ${TopMake} REPO_TOP=$(pwd) BUILD_DIR=${BuildDir} CFLAGS="${CFlags}" -j

# Install TODO
echo "Bin: ${GListBin[@]}"

# Clean Temp
rm -vf ${TopMake}
rm -rvf $TempDir
